import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;
import java.text.SimpleDateFormat;
import java.util.Calendar;

import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JTextField;
import javax.swing.Timer;

//import MainScreen.MyClockActionListener;

@SuppressWarnings("serial")
public class UserPrompt extends JFrame{
	JLabel user, pass, curDateTime;
	JTextField userId;
	JPasswordField passWord;
	JButton submit, cancel;
	ImageIcon ii = new ImageIcon(this.getClass().getResource("images/uprompt.png"));
	private Image bgImage = ii.getImage();
	private int uID, statAt=1;
	int sit;
	JPanel uPanel;
	
	public UserPrompt(int c){
		//GUI constructor
		//initialize
		super("");

		uPanel = new JPanel() {
			protected void paintComponent(Graphics g){
				g.drawImage(bgImage, 0, 0, null);
				super.paintComponent(g);
			}
		};

		//set adjustments
		uPanel.setLayout (null);


		curDateTime = new JLabel();

		user = new JLabel("User ID:");
		pass = new JLabel("Password:");
		userId = new JTextField();
		passWord = new JPasswordField();
		submit = new JButton("Submit");
		cancel = new JButton ("Cancel");


		curDateTime.setBounds(25, 60, 200, 25);
		user.setBounds (50, 90, 100, 25);
		pass .setBounds (50, 130, 100, 25);
		userId.setBounds (130, 90, 140, 25);
		passWord.setBounds (130, 130, 140, 25);
		submit.setBounds (50, 170, 100, 25);
		cancel.setBounds (170, 170, 100, 25);

		curDateTime.setForeground(Color.WHITE);
		user.setForeground(Color.WHITE);
		pass.setForeground(Color.WHITE);
		submit.setForeground(Color.WHITE);
		cancel.setForeground(Color.WHITE);
		submit.setBackground(Color.BLACK);
		cancel.setBackground(Color.BLACK);

		curDateTime.setFont(new Font("sansserif", Font.BOLD, 12));

		sit = c;
		if(sit == 1)
		{	setTitle("Log In");
		curDateTime.setVisible(false); }
		else if (sit == 2)
			setTitle("Time In");
		else
			setTitle("Time Out");

		//add components

		uPanel.setOpaque( false );
		uPanel.add(curDateTime);
		uPanel.add(user);
		uPanel.add(pass);
		uPanel.add(userId);
		uPanel.add(passWord);
		uPanel.add(submit);
		uPanel.add(cancel);

		add(uPanel);

		curDateTime.setText(now("MMMM dd, yyyy h:mm:ss a"));

		setSize(356, 243);
		setVisible(true);
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		setResizable(false);


		Timer timer = new Timer(1000, new MyClockActionListener());
		timer.start();

		//action listeners

		cancel.addActionListener(new ActionListener(){
			public void actionPerformed(ActionEvent e){
				setVisible(false);
				MainPanel.goToPage(0);
			}
		});

		submit.addActionListener(new ActionListener(){
			public void actionPerformed(ActionEvent e){

				try{
					if(getUserid().equals("admin"))
						setUserid();

					ConnectionFactory myFactory = ConnectionFactory.getFactory();
			        Connection conn = myFactory.getConnection();

					Statement stat = conn.createStatement();
					ResultSet res = stat.executeQuery("SELECT * FROM bernalcompany.employee WHERE idemployee ='" + getUserid()
							+ "' and password='" + getPassword() + "'");
					PreparedStatement checkT;
					checkT = conn.prepareStatement("SELECT timeIn, timeOut FROM bernalcompany.attendance WHERE idemployee ='" + getUserid()
							+ "' and dateSal='" + now("yyyy-MM-dd") + "'");
					ResultSet res1 = checkT.executeQuery();
					
					if(res.next())
					{ 

						if(res.getString("status").equals("Inactive"))
							JOptionPane.showMessageDialog(uPanel, "User is already inactive.", "Error", JOptionPane.ERROR_MESSAGE);
						else {
							setVisible(false);
							
							MainPanel.setUID(Integer.parseInt(getUserid()));
							switch(sit)
							{
							case 1: 
								if(getUserid().equals("36"))
								{		MainPanel.goToPage(3);
								}
								else
									MainPanel.goToPage(2);
								break;
							case 2: 
								if(res1.next())
									JOptionPane.showMessageDialog(uPanel, "You have already timed in for the day", "Error", JOptionPane.ERROR_MESSAGE);
								else{
									PreparedStatement in;
									in = conn.prepareStatement("INSERT INTO attendance(dateSal, timeIn, idemployee, stat) VALUES(?,?,?,?)");
									in.setString(1, now("yyyy-MM-dd"));
									in.setString(2, now("HH:mm:ss"));
									in.setString(3, getUserid());
									if(now("HH:mm:ss").equals("08:00:00"))
										statAt = 1;
									else
										statAt = 2;
									in.setInt(4, statAt);
									in.executeUpdate();
									JOptionPane.showMessageDialog(uPanel, "You have timed in for the day. Thank you!");
								}
								MainPanel.goToPage(0);
								break;
							case 3:
								if(res1.next()){
									if(!res1.getBoolean("timeOut")){
										PreparedStatement out;
										out = conn.prepareStatement("UPDATE attendance set timeOut = ? where dateSal = ? and idemployee = ?");
										out.setString(1, now("HH:mm:ss"));
										out.setString(2, now("yyyy-MM-dd"));
										out.setString(3, getUserid());
										out.executeUpdate();
										JOptionPane.showMessageDialog(uPanel, "You have successfully timed out. Thank you!");
									}else
										JOptionPane.showMessageDialog(uPanel, "You have already timed out for the day.", "Error", JOptionPane.ERROR_MESSAGE);	
								}else		
									JOptionPane.showMessageDialog(uPanel, "You haven't timed in for the day.", "Error", JOptionPane.ERROR_MESSAGE);
								MainPanel.goToPage(0);
								break;
							}
						}  
					}
					else
					{
						JOptionPane.showMessageDialog(uPanel, "Invalid User ID/Password. Try again!", "Error", JOptionPane.ERROR_MESSAGE);
						setVisible(true);
					}
					
					conn.close();


				}catch(Exception ex){

					ex.printStackTrace();
				}
			}
		});

	}

	public void setUserid(){
		userId.setText("36");
	}

	public String getUserid() {
		return userId.getText().trim();
	}

	public  int getUID(){
		return uID;
	}

	public String getPassword() {
		return new String(passWord.getPassword());
	}

	class MyClockActionListener implements ActionListener{
		public void actionPerformed(ActionEvent e){
			curDateTime.setText(now("MMMMM dd, yyyy h:mm:ss a"));
		}
	}

	public static String now (String dateFormat){

		Calendar cal = Calendar.getInstance();
		SimpleDateFormat dateTime = new SimpleDateFormat(dateFormat);
		return dateTime.format(cal.getTime());
	}

}
